package com.example.demo.controller;

import com.example.demo.common.ResultAjax;
import com.example.demo.common.SessionUtils;
import com.example.demo.config.ThreadPoolConfig;
import com.example.demo.model.ArticleInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.model.vo.UserInfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author: wenjingyuan
 * @Date: 2023/08/01/10:38
 * @Description:
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    private static  final int Desc_Len=120;//文章简介长度
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * 我的文章列表
     * @param request
     * @return
     */
    @RequestMapping("/mylist")
    public ResultAjax myList(HttpServletRequest request){

        //1.得到当前登录的用户
        UserInfo userInfo = SessionUtils.getUser(request);
        if(userInfo==null){
            //未登录
            return ResultAjax.fail(-1,"请先登录！");
        }
        //2.使用用户id查询文章列表
        List<ArticleInfo> list=articleService.getListByUid(userInfo.getId());
        //使用多线程进行对list分割处理
        if(list!=null && list.size()>0){
            //已经有文章
            list.stream().parallel().forEach((art)->{
                //并且大于120
                if(art.getContent().length()>Desc_Len){
                    art.setContent(art.getContent().substring(0,Desc_Len));
                }
            });
        }
        //3.将结果返回给用户
        return ResultAjax.succ(list);
    }

    /**
     * 删除文章操作
     */
    @RequestMapping("/del")
    public ResultAjax del(Integer aid,HttpServletRequest request){
        //1.参数效验
        if(aid==null ||aid<=0){
            return ResultAjax.fail(-1,"参数错误");
        }
        //2.得到当前登陆的用户
        UserInfo userInfo=SessionUtils.getUser(request);
        if(userInfo==null){
            //未登录
            return ResultAjax.fail(-2,"请先登录！");
        }
        //3和4可以合并where id=id and uid=uid
        int result=articleService.del(aid, userInfo.getId());
        //3.判断文章的归属人
        //4.删除操作
        //5.将结果返回给用户
        return ResultAjax.succ(result);
    }

    /**
     * 添加文章操作
     */
    @RequestMapping("/add")
    public ResultAjax add(ArticleInfo articleInfo,HttpServletRequest request){
        //1.效验参数
        if (articleInfo==null || !StringUtils.hasLength(articleInfo.getTitle())
        ||! StringUtils.hasLength(articleInfo.getContent())){
            //参数错误
            return ResultAjax.fail(-1,"参数错误");
        }
        //2.组装数据
        UserInfo userInfo=SessionUtils.getUser(request);
        if(userInfo==null){
            return ResultAjax.fail(-2,"请先登录");
        }
        articleInfo.setUid(userInfo.getId());
        //3.传入数据库
        int result =articleService.add(articleInfo);
        //4.将结果返回给用户
        return ResultAjax.succ(result);
    }

    /**
     * 查询自己的文章详情页
     */
    @RequestMapping("/update_init")
    public ResultAjax updateInit(Integer aid,HttpServletRequest request){
        //1.效验参数
        if(aid==null || aid<=0){
            return ResultAjax.fail(-1,"参数错误");
        }
        //2.得到当前登录用户
        UserInfo userInfo=SessionUtils.getUser(request);
        if(userInfo==null){
            return ResultAjax.fail(-2,"请先登录");
        }
        //3.查询文章并验证归属人
       ArticleInfo articleInfo=articleService.getArticleByIdAndUid(aid,userInfo.getId());
        //4.将结果返回给前端
        return ResultAjax.succ(articleInfo);
    }

    /*
    修改文章信息
     */
    @RequestMapping("/update")
    public ResultAjax update(ArticleInfo articleInfo,HttpServletRequest request){
        //1.效验参数
        if(articleInfo==null ||!StringUtils.hasLength(articleInfo.getTitle())
                ||!StringUtils.hasLength(articleInfo.getContent())
                ||articleInfo.getId()==0){
            return ResultAjax.fail(-1,"参数错误");
        }
        //2.得到当期登录用户 并给uid赋值
        UserInfo userInfo=SessionUtils.getUser(request);
        if(userInfo==null){
            return ResultAjax.fail(-2,"请先登录");
        }
        articleInfo.setUid(userInfo.getId());
        //3.修改文章 并验证归属人
        int result=articleService.update(articleInfo);
        //4.将结果返回给前端
        return ResultAjax.succ(result);
    }

    /*
    查询文章的详情页
     */
    @RequestMapping("/detail")
    public ResultAjax detail(Integer aid) throws ExecutionException, InterruptedException {
        //1.效验参数
        if(aid==null || aid<=0){
            return ResultAjax.fail(-1,"参数有误");
        }
        //2.查询文章的详情
        ArticleInfo articleInfo=articleService.detail(aid);
        if(articleInfo==null || articleInfo.getId()<=0){
            return ResultAjax.fail(-1,"参数有误");
        }
        //3.根据uid查询用户的详情
        FutureTask<UserInfoVO> userTask=new FutureTask<>(()->{
            int uid=articleInfo.getUid();
            return userService.getUserDetail(uid);
        });
        taskExecutor.submit(userTask);
        //4.根据uid查询用户的文章总数
        FutureTask<Integer> artTask=new FutureTask<>(()->{
            int uid=articleInfo.getUid();
            return articleService.getArtCount(uid);
        });
        //提交任务
        taskExecutor.submit(artTask);
        //5.组装数据
        UserInfoVO userInfoVO=userTask.get();//等他们执行结束
        int artCount=artTask.get();//等他们执行结束
        userInfoVO.setArtCount(artCount);
        //6.将结果返回给前端
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("user",userInfoVO);
        hashMap.put("art",articleInfo);
        return ResultAjax.succ(hashMap);
    }

    /**
     * 访问量加1的操作
     */
    @RequestMapping("/increment_rcount")
    public ResultAjax incrementRcount(Integer aid){
        //效验参数
        if(aid==null || aid<=0){
            return ResultAjax.fail(-1,"参数有误");
        }
        //更改数据库
        int result=articleService.incrementRcount(aid);
        //将结果传给后端
        return ResultAjax.succ(result);
    }

    /**
     * 查询分页功能
     *
     */
    @RequestMapping("/getlistbysize")
    public ResultAjax getListBySize(Integer pindex,Integer psize) throws ExecutionException, InterruptedException {
        //1.加工参数
        if(pindex==null || pindex<1){
            pindex=1;//参数默认
        }
        if(psize==null || psize<1){
            psize=2;
        }
        //2.并发处理两条查询线(文章列表和总页数的查询)
        Integer finalPsize = psize;
        Integer finalPindex = pindex;
        FutureTask<List<ArticleInfo>> listTask=new FutureTask<>(()->{
            int offset= finalPsize *(finalPindex -1);
            return articleService.getListBySize(finalPsize,offset);
        });
        FutureTask<Integer> sizeTask=new FutureTask<>(()->{
           //总条数
            int totalCount=articleService.getCount();
            //总共有多少页=总条数/每页的条数  向上取整
            double num=(totalCount*1.0)/(finalPsize*1.0);
            int size= (int) Math.ceil(num);
            return size;
        });
        //3.组装数据
        taskExecutor.submit(listTask);
        taskExecutor.submit(sizeTask);
        List<ArticleInfo> list=listTask.get();
        int size=sizeTask.get();
        HashMap<String,Object> map=new HashMap<>();
        map.put("list",list);
        map.put("size",size);
        //4.将结果返回给后端
        return ResultAjax.succ(map);
    }
}
